package com.a918.controller;


import com.a918.dao.ContentTypeMapper;
import com.a918.dao.MemBwgMapper;
import com.a918.dto.*;
import com.a918.entity.*;
import com.a918.service.ContentCheckService;
import com.a918.service.BackContentService;
import com.a918.service.UserService;
import com.a918.service.FrontService;
import com.a918.service.MemberService;
import com.a918.service.BackShowService;
import com.a918.util.FileUtil;
import com.a918.util.IPGet;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;


@Controller
public class BackContentController {

    private BackContentService backContentService;
    private ContentCheckService contentCheckService;
    private UserService userService;
    private FrontService frontService;
    private ContentTypeMapper contentTypeMapper;
    private MemBwgMapper memBwgMapper;

    @Autowired
    public BackContentController(BackContentService backContentService, ContentCheckService contentCheckService,
                                 UserService userService, FrontService frontService,
                                 ContentTypeMapper contentTypeMapper, MemBwgMapper memBwgMapper, BackShowService backShowService) {
        this.backContentService = backContentService;
        this.contentCheckService = contentCheckService;
        this.userService = userService;
        this.frontService = frontService;
        this.contentTypeMapper = contentTypeMapper;
        this.memBwgMapper = memBwgMapper;
    }


    @GetMapping("/content")
    public String content(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        switch (type) {
            //添加
            case "add":
                return "back/content_add";
            //草稿箱
            case "cgx":
                return "back/content_drafts";
            //待修改
            case "dxg":
                return "back/content_dxg";
            //待审核
            case "dsh":
                return "back/content_dsh";
            //已发布
            case "yfb":
                return "back/content_yfb";
            case "pic":
                List<Content> contentList = backContentService.selectContentWithNoCover();
                model.addAttribute("contentList", contentList);
                return "back/content_pic";
        }
        return "index";
    }

    @PostMapping("/addcontent")
    @ResponseBody
    public String addContent(@RequestBody Content record, HttpServletRequest request) {
        userService.insertlog("上传联盟章程","upload_lmzc",(String) request.getSession().getAttribute("username"), IPGet.getIp(request));
        Date addtime = new Date();
        record.setViewnum(0);
        record.setWeight(50);
        record.setAddtime(addtime);
        record.setAdduserid((Integer) request.getSession().getAttribute("id"));
        try {
            backContentService.insertBackContent(record);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/changeContent")
    @ResponseBody
    public String changeContent(@RequestBody Content record, HttpServletRequest request) {
        Date addtime = new Date();
        Integer adduserid = (Integer) request.getSession().getAttribute("id");
        record.setAddtime(addtime);
        record.setAdduserid(adduserid);
        try {
            backContentService.deleteById(record.getId());
            backContentService.insertBackContent(record);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/returnContent")
    @ResponseBody
    public String returnContent(@RequestBody Content record, HttpServletRequest request) {
        Date addtime = new Date();
        Integer adduserid = (Integer) request.getSession().getAttribute("id");
        record.setAddtime(addtime);
        record.setAdduserid(adduserid);
        try {
            backContentService.updateBackContent(record);
            contentCheckService.deleteByContentId(record.getId());
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @GetMapping("/frontunion")
    public String frontUnion(HttpServletRequest req) {
        String type = req.getParameter("type");
        switch (type) {
            case "dsh":
                return "back/union_dsh";
            case "ytg":
                return "back/union_ytg";
        }
        return "back/union_ytg";
    }

    @GetMapping("/museum")
    public String museum(HttpServletRequest req) {
        String type = req.getParameter("type");
        switch (type) {
            case "dsh":
                return "back/museum_dsh";
            case "ytg":
                return "back/museum_ytg";
        }
        return "back/museum_dsh";
    }


    @PostMapping("/getContentlist")
    @ResponseBody
    public Object getContentlist(@RequestParam Map<String, String> paramMap) {
        PageInfo<PublishData> pageInfo = backContentService.getContentlist(paramMap);
        return new TableResponse(0, "查询成功", pageInfo.getList(), pageInfo.getTotal());
    }


    @GetMapping("/getOpinion")
    public String getOpinion(Model model, HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        String type = request.getParameter("type");
            switch (type) {
            case "content":
                ContentCheck contentCheck = contentCheckService.selectByContentId(id);
                String opinion = contentCheck.getOpinion();
                model.addAttribute("opinion", opinion);
                break;
            case "user": {
                FrontFcCheck frontFcCheck = backContentService.getFrontFcCheckByIdType(id, "user");
                model.addAttribute("opinion", frontFcCheck.getOpinion());
                break;
            }
            case "museum": {
                FrontFcCheck frontFcCheck = backContentService.getFrontFcCheckByIdType(id, "museum");
                model.addAttribute("opinion", frontFcCheck.getOpinion());
                break;
            }
        }
        return "back/opinion";
    }

    @PostMapping("/delContent")
    @ResponseBody
    public String delContent(Integer id) {
        try {
            backContentService.deleteById(id);
            frontService.deleteCoverByContentid(id);
            contentCheckService.deleteByContentId(id);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/confirmSetback")
    @ResponseBody
    public String confirmSetback(@RequestBody FrontFcCheck record, HttpServletRequest request) {
        try {
            System.out.println(record.getCheckid());
            String type = record.getType();
            Date creatTime = new Date();
            if (type.equals("content")) {
                System.out.println(type);
                ContentCheck contentCheck = new ContentCheck();
                Integer id = (Integer) request.getSession().getAttribute("id");
                contentCheck.setCreattime(creatTime);
                User user = userService.getUserById(id);
                String checkerId = user.getUsername();
                contentCheck.setCheckerid(checkerId);
                contentCheck.setOpinion(record.getOpinion());
                contentCheck.setContentid(record.getCheckid());
                contentCheckService.setback(contentCheck);

                Content content = backContentService.getBackContentById(contentCheck.getContentid());
                content.setStatus("dxg");
                backContentService.updateBackContent(content);
                return "success";
            } else if (type.equals("museum")) {
                record.setCreattime(creatTime);
                record.setCheckerid((Integer) request.getSession().getAttribute("id"));
                backContentService.insertFrontFcCheck(record);
                FrontMember frontMember = backContentService.getFrontMemberById(record.getCheckid());
                frontMember.setStatus("dxg");
                backContentService.updateFrontMember(frontMember);
                System.out.println(type);
                return "success";
            } else {
                System.out.println(type);
                record.setCreattime(creatTime);
                record.setCheckerid((Integer) request.getSession().getAttribute("id"));
                backContentService.insertFrontFcCheck(record);
                FrontUnion frontUnion = backContentService.getFrontUnionById(record.getCheckid());
                frontUnion.setStatus("dxg");
                backContentService.updateFrontUnion(frontUnion);
                return "success";
            }
        } catch (Exception e) {
            return "error";
        }
    }


    @PostMapping("/publishContent")
    @ResponseBody
    public String publishContent(@RequestBody Content record, HttpServletRequest request) {
        Date addtime = new Date();
        Integer adduserid = Integer.parseInt(request.getParameter("id"));
        record.setAddtime(addtime);
        record.setAdduserid(adduserid);
        record.setWeight(0);
        Integer publishuserid = (Integer) request.getSession().getAttribute("id");
        record.setPublisherid(publishuserid);
        record.setPublishtime(addtime);
        try {
            backContentService.updateBackContent(record);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/editWeight")
    @ResponseBody
    public String editWeight(Integer id, Integer weight) {
        Content content = new Content();
        content.setId(id);
        content.setWeight(weight);
        try {
            backContentService.updateBackContent(content);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }


    @PostMapping("/postNews")
    @ResponseBody
    public String postNews(Integer id, HttpServletRequest request) {
        Date publishtime = new Date();
        Content content = new Content();
        content.setId(id);
        content.setStatus("yfb");
        content.setWeight(0);
        Integer publishuserid = (Integer) request.getSession().getAttribute("id");
        content.setPublisherid(publishuserid);
        content.setPublishtime(publishtime);
        try {
            backContentService.updateBackContent(content);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @GetMapping("/moreContent")
    public String moreContent(HttpServletRequest request, Model model) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        String show = request.getParameter("show");
        model.addAttribute("show", show);
        Content content = backContentService.getBackContentById(id);
        model.addAttribute("title", content.getTitle());
        String type = contentTypeMapper.selectByPrimaryKey(content.getTypeid()).getName();
        model.addAttribute("type", type);
        model.addAttribute("id", content.getId());
        model.addAttribute("context", content.getContext());
        return "back/content_more";
    }

    @GetMapping("/museumMore")
    public String museumMore(HttpServletRequest request, Model model){
        Integer id = Integer.parseInt(request.getParameter("id"));
        FrontMember record = backContentService.getFrontMemberById(id);
        System.out.println(record.getId());
        model.addAttribute("record", record);
        model.addAttribute("industry", memBwgMapper.selectByPrimaryKey(record.getBwgid()).getIndustrytype());
        return "back/museum_more";
    }


    @GetMapping("/unionMore")
    public String unionMore(HttpServletRequest request, Model model) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        FrontUnion record = backContentService.getFrontUnionById(id);
        model.addAttribute("record", record);
        return "back/union_more";
    }

    @GetMapping("/setback")
    public String setback(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        Integer id = Integer.parseInt(request.getParameter("id"));
        System.out.println(type);
        if (type.equals("content")) {
            Content content = backContentService.getBackContentById(id);
            model.addAttribute("title", content.getTitle());
        } else if (type.equals("museum")) {
            FrontMember frontMember = backContentService.getFrontMemberById(id);
            model.addAttribute("title", frontMember.getName());
        } else {
            FrontUnion frontUnion = backContentService.getFrontUnionById(id);
            model.addAttribute("title", userService.getUserById(frontUnion.getUserid()).getUsername());
        }
        model.addAttribute("id", id);
        model.addAttribute("type", type);
        return "back/setback";
    }


    @GetMapping("/draftEdit")
    public String draftEdit(HttpServletRequest request, Model model) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        String show = request.getParameter("show");
        Content content = backContentService.getBackContentById(id);
        model.addAttribute(content);
        model.addAttribute("show", show);
        return "back/content_edit";
    }

    @GetMapping("/dxgEdit")
    public String dxgEdit(HttpServletRequest request, Model model) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        Content content = backContentService.getBackContentById(id);
        model.addAttribute(content);
        return "back/dxg_edit";
    }

    @PostMapping("/museumList")
    @ResponseBody
    public Object bwgList(@RequestParam Map<String, String> paramMap, HttpServletRequest req) {
        String status = req.getParameter("status");
        PageInfo<BwgData> pageInfo = backContentService.selectMuseumList(paramMap, status);
        return new TableResponse(0, "查询成功", pageInfo.getList(), pageInfo.getTotal());
    }

    @PostMapping("/unionList")
    @ResponseBody
    public Object unionList(@RequestParam Map<String, String> paramMap, HttpServletRequest req) {
        String status = req.getParameter("status");
        PageInfo<UnionData> pageInfo = backContentService.selectUnionList(paramMap, status);
        return new TableResponse(0, "查询成功", pageInfo.getList(), pageInfo.getTotal());
    }

    @PostMapping("/datacover")
    @ResponseBody
    public Object dataCover(@RequestParam Map<String, String> paramMap) {
        PageInfo<CoverData> pageInfo = frontService.getAllCoverData(paramMap);
        return new TableResponse(0, "查询成功", pageInfo.getList(), pageInfo.getTotal());
    }


    @PostMapping("/upload_cover")
    @ResponseBody
    public JSONObject upload_cover(MultipartFile file, HttpServletRequest request){
        JSONObject res = new JSONObject();
        res.put("code",0);
        res.put("msg",0);
        String uploadtag = FileUtil.uploadfile(file,"image//cover");
        res.put("data",uploadtag);
        return res;
    }

    @PostMapping("/addcover")
    @ResponseBody
    public String addCover(@RequestBody Cover cover, HttpServletRequest request) {
        Date createtime = new Date();
        cover.setCreattime(createtime);
        try {
            frontService.insertCover(cover);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/delUnion")
    @ResponseBody
    public String delUnion(@RequestParam Integer id) {
        try {
            backContentService.deleteFrontUnionById(id);
            backContentService.delFrontFcCheckByIdType(id, "user");
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }

    @PostMapping("/delcover")
    @ResponseBody
    public String delCover(@RequestParam Integer coverId) {
        System.out.println("删除图片id: " + coverId);

        frontService.deleteCoverById(coverId);
        return "success";
    }


    @GetMapping("/museum_more")
    public String BwgztMore(HttpServletRequest request, Model model) {

        Integer bwgztId = Integer.valueOf(request.getParameter("id"));
        FrontMember frontMember = backContentService.getFrontMemberById(bwgztId);
        if (frontMember.getPicid() == null) {
            frontMember.setPicid("/static/images/bwglogo/0.png");
        }
        model.addAttribute("id", frontMember.getId());
        model.addAttribute("name", frontMember.getName());
        model.addAttribute("province", frontMember.getProvince());
        model.addAttribute("introduct", frontMember.getIntroduct());
        model.addAttribute("show", "yes");
        model.addAttribute(frontMember);
        String picPath = frontMember.getPicid();
        model.addAttribute("picpath", picPath);
        return "back/show_bwgztinfo";
    }

    @PostMapping("/postbwgzt")
    @ResponseBody
    public String PostBwgzt(@RequestParam Integer id) {
        try {
            FrontMember frontMember = backContentService.getFrontMemberById(id);
            frontMember.setStatus("yfb");
            backContentService.updateFrontMember(frontMember);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }
    @GetMapping("/more_Union")
    public String frontUnionMore(HttpServletRequest request, Model model) {
        Integer frontUnionId = Integer.valueOf(request.getParameter("id"));
        FrontUnion frontUnion = backContentService.getFrontUnionById(frontUnionId);
        String username = userService.getUserById(frontUnion.getUserid()).getUsername();

        model.addAttribute("frontUnion", frontUnion);
        model.addAttribute("name", username);
        model.addAttribute("show", "yes");
        return "back/show_frontunioninfo";
    }

    @PostMapping("/postfrontunion")
    @ResponseBody
    public String PostFrontUnion(@RequestParam Integer id) {
        try {
            FrontUnion frontUnion = backContentService.getFrontUnionById(id);
            frontUnion.setStatus("yfb");
            backContentService.updateFrontUnion(frontUnion);
            return "success";
        } catch (Exception e) {
            return "error";
        }
    }
}


